<?php
namespace app\service;


use app\model\MemberModel;
use app\model\PromotionPosterModel;
use Tinywan\Storage\Storage;
use const support\CORRECT;
use EasyWeChat\Factory;
use const support\DISTRIBUTION_SHARE_WECHAT_HOME;

class PromotionPosterService
{

    //获取推广海报信息
    public static function getPromotionPoster($memberId): array
    {
        $info= PromotionPosterModel::where([
            'member_id'=>$memberId,
            'status'=>CORRECT
        ])->select(['id','promotion_poster_url','promotion_qrcode_url'])->first();
        //不存在时创建二维码和海报
        if (empty($info->id)){
            //获取用户标识
            $memberSn=MemberModel::where('id',$memberId)->where('status',CORRECT)->value('member_sn');
            $qrcodeUrl='';
            //生成微信二维码
            $app = Factory::miniProgram(config('wechat.mini_program'));
            $response = $app->app_code->get(sprintf("%s?invite_code=%s",DISTRIBUTION_SHARE_WECHAT_HOME,$memberSn),[
                'env_version'=>checkRuntimeEnv()?'release':'trial'
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path('qrcode'),md5(time()).'.png');
                $filename=sprintf('%s/%s',runtime_path('qrcode'),$filename);
                $extension = pathinfo($filename, PATHINFO_EXTENSION);
                //将数据上传
                $base64=sprintf('data:image/jpeg;base64,%s',base64_encode(file_get_contents($filename)));
                $data =Storage::disk(Storage::MODE_OSS, false)->uploadBase64($base64,$extension);
                $qrcodeUrl=$data['url']??'';
                unlink($filename);
            }
            //生成海报
            PromotionPosterModel::insertGetId([
                'promotion_qrcode_url'=>$qrcodeUrl,
                'member_id'=>$memberId,
                'create_time'=>time()
            ]);
        }else{
            $qrcodeUrl=$info->promotion_qrcode_url;
        }
        return [
            'promotion_poster_url'       =>$qrcodeUrl,
            'promotion_qrcode_url'       =>$qrcodeUrl
        ];
    }


}